package com.smforj.ssm.modules.eslib.service.impl;

import java.util.Date;

import org.apache.commons.lang3.NotImplementedException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.smforj.ssm.frame.core.exception.ServiceException;
import com.smforj.ssm.frame.core.utils.StringEx;
import com.smforj.ssm.frame.core.web.domain.DataResult;
import com.smforj.ssm.frame.core.web.domain.DataResult.DataStatus;
import com.smforj.ssm.modules.eslib.domain.vo.LibBookVo;
import com.smforj.ssm.modules.lib.constant.BorrowType;
import com.smforj.ssm.modules.lib.constant.TerminalType;
import com.smforj.ssm.modules.lib.dao.CoreRecordDao;
import com.smforj.ssm.modules.lib.dao.SysBookinfoDao;
import com.smforj.ssm.modules.lib.domain.CheckOutResponse;
import com.smforj.ssm.modules.lib.domain.CoreCurrentrecord;
import com.smforj.ssm.modules.lib.domain.LibraryRequest;
import com.smforj.ssm.modules.lib.domain.LoginUser;
import com.smforj.ssm.modules.lib.domain.SysBook;
import com.smforj.ssm.modules.lib.domain.SysConfig;
import com.smforj.ssm.modules.lib.domain.SysReader;
import com.smforj.ssm.modules.lib.domain.SysReaderWechat;
import com.smforj.ssm.modules.lib.domain.Terminal;
import com.smforj.ssm.modules.lib.domain.query.SysBookQuery;
import com.smforj.ssm.modules.lib.domain.vo.SysBookVo;
import com.smforj.ssm.modules.sys.service.SysReaderService;
import com.smforj.ssm.modules.wc.service.BusinessService;
import com.smforj.ssm.util.DateFormat;
import com.smforj.ssm.util.UUIDUtils;

/***
 * 该类仅执行智能系统进行自助借还操作，与图书管理系统是独立分开的，事务处理也针对本对象的方法
 * 目前该类的实现还是按原来系统的业务逻辑，后期会根据实际情况进行更改优化
 * 
 * @author Haijun Gao 
 * @date 2016-8-6 上午11:48:18
 * @desp http://www.cnblogs.com/saga5998/
 * @email 573107773@qq.com
 */
@Service("esbusinessService")
@Description("业务处理对象")
@Transactional
public class EsBusinessServiceImpl implements BusinessService {
	private Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	@Qualifier("sysBookinfoDao")
	private SysBookinfoDao sysBookinfoDao;  
/*	@Autowired
	private SysConfigMapper sysConfigDao;*/
/*	@Autowired
	private LibraryService libraryService; */
	@Autowired
	private SysReaderService sysReaderService;  
/*	@Autowired
	private SysReaderWechatMapper readerWechatDao;*/
	
	@Autowired
	@Qualifier("coreRecordDao")
	private CoreRecordDao coreRecordDao; 

	/***
	 * 根据code 查询图书信息
	 * @param code 图书名称或id
	 * @return
	 * @date 2016-8-1 下午2:29:45
	 */
	@Override
	public SysBookVo getBookInfo(String code) { 
		SysBookQuery book = new SysBookQuery(); 
		if(StringEx.isContainChinese(code))
			book.setBookNameLike(code);
		else
			book.setBarcode(code);
		SysBookVo bookVo = sysBookinfoDao.selectOne(book);  
		return bookVo;
	}  

	/***
	 * 该方法采用先金至系统再图书管理系统的逻辑进行  
	 * 1、金至系统 记录借阅日志 
	 * 2、金至系统 保存当前借阅记录
	 * 3、金至系统 修改借阅标志
	 * 
	 */
	@Override   
	public DataResult doBorrowBook(SysBookVo book,Terminal terminal,LoginUser user) {  
		//返回信息
		DataResult result = new DataResult();   
		//book = sysBookinfoDao.selectOne(book);
		System.out.println("doBorrowBook book:"+book);
		
		//借阅记录
/*		CoreCirculationLog cr = new CoreRecordLog(); 
		cr.setId(UUIDUtils.random());
		cr.setBookId(book.getId());  
		cr.setReaderId(user.getReader().getId());
		cr.setTerminalId(terminal.getId());
		cr.setTerminalType(terminal.getType());
		cr.setRecordDate(new Date());
		cr.setRecordType(RecordType.BORROW); 
		cr.setRemark(terminal.getRemark() == null ? "" : terminal.getRemark().toString());  */
		
		//当前记录
		CoreCurrentrecord crecord = new CoreCurrentrecord(); 
		crecord.setId(UUIDUtils.random());
		crecord.setBarcode(book.getBarcode());
		crecord.setBookName(book.getBookname());
		crecord.setBorrowType(BorrowType.BORROW);
		crecord.setCallNum(null);//索书号
		crecord.setIsRenewed(false);
		crecord.setNeedReturnDate(null);
		crecord.setReaderId(user.getReader().getId());
		//crecord.setRecordId(cr.getId());
		//crecord.setRemark(terminal.getRemark() == null ? "" : terminal.getRemark().toString());
		crecord.setRfid(book.getRfid());  
		crecord.setTerminalId(terminal.getId());
		crecord.setTerminalType(terminal.getTerminalType()); 
		crecord.setNeedReturnDate(book.getNeedReturnDate() == null ? new Date() : book.getNeedReturnDate());
		crecord.setBorrowDate(book.getOccurDate() == null ? new Date() : book.getOccurDate());
		
		
		try{ 
			//保存记录信息
			//int i = coreRecordDao.insert(cr); 
			//System.out.println("保存记录信息 "+i);
			//保存当前信息
/*			CoreCurrentrecord cc =  coreCurrentRecordDao.selectByRfid(book.getRfid()); 
			if(cc == null) 
				coreCurrentRecordDao.insert(crecord);
			else //存在则更新
			{
				crecord.setId(cc.getId()); 
				coreCurrentRecordDao.updateByPrimaryKey(crecord);
			}  */
			//更新图书状态(后期将不再使用)以当前记录为标准
			//sysBookinfoDao.updateStatusByRFID(book);
			
			result.setStatus(DataStatus.OK);
			result.setMessage("借阅成功"+getCheckOutMsg(crecord.getBookName(),user.getReader().getReaderName(),
					DateFormat.dateToString(crecord.getBorrowDate(),DateFormat.FORMATDATE),
					DateFormat.dateToString(crecord.getNeedReturnDate(),DateFormat.FORMATDATE))); 
		}catch(Exception ex)
		{
		    log.error("借阅异常："+ex.getCause().getMessage()); 
			result.setStatus(DataStatus.ERROR);
			result.setMessage("借阅异常："+ex.getMessage()); 
			throw new ServiceException(ex); 
		} 
		return result;
	} 
	
	private String getCheckOutMsg(String bookName,String readername,String date,String rdate)
	{
		return String.format("\r\n图书名称：%s 借阅者：%s \r\n借阅日期：%s 应还日期：%s", bookName,readername,date,rdate);
	}

	/***
	 * 该方法采用先金至系统再图书管理系统的逻辑进行 
	 * 1、记录归还日志
	 * 2、删除当前借阅信息
	 * 3、修改借阅标志
	 * 
	 */
	@Override 
	public DataResult doReturnBook(SysBookVo book,Terminal terminal,LoginUser user) { 
		
		DataResult result = new DataResult();  
		CoreCurrentrecord cbr = null;
		try{
			//查询当前借阅信息
			//cbr = coreCurrentRecordDao.selectByRfid(book.getRfid()); 
		}catch(Exception ex)
		{
			log.error("查询记录信息异常："+ex.getCause().getMessage());
			cbr = null;
		}
		if(cbr == null)
		{
			result.setStatus(DataStatus.ERROR);
			result .setMessage("没有相应的借阅记录");
			return result;
		} 
		
/*		//借阅记录
		CoreCirculationLog cr = new CoreCirculationLog();  
		cr.setBookId(book.getId());  
		cr.setReaderId(user.getReader().getId());
		cr.setTerminalId(terminal.getId());
		cr.setTerminalType(terminal.getType());
		cr.setRecordDate(new Date());
		cr.setRecordType(RecordType.RETURN); 
		cr.setRemark(terminal.getRemark() == null ? "" :terminal.getRemark().toString()); 
		
		//更新图书状态为已还 
		
		try{ 
			//保存记录信息
			coreRecordDao.insert(cr);  
			//删除借阅当前记录
		    coreCurrentRecordDao.deleteByRFID(book.getRfid());
			//更新图书状态(后期将不再使用)以当前记录为标准
			sysBookinfoDao.updateStatusByRFID(book);
			
			result.setStatus(DataStatus.OK);
			result.setMessage("还书成功"); 
		}catch(Exception ex)
		{
			log.error("还书异常："+ex.getCause().getMessage()); 
			result.setStatus(DataStatus.ERROR);
			result.setMessage("还书异常："+ex.getMessage()); 
			throw new ServiceException(ex); 
		} */
		return result;
	}

	@Override 
	public DataResult doRenewBook(SysBookVo book,Terminal terminal,LoginUser user) { 
		//返回信息
		DataResult result = new DataResult();  
/*		CoreCurrentrecord crecord = null;
		try{
			//根据RFID查询当前借阅信息
			crecord = coreCurrentRecordDao.selectByRfid(book.getRfid()); 
		}catch(Exception ex)
		{
			log.error("查询记录信息异常："+ex.getMessage());
			crecord = null;
		}
		if(crecord == null)
		{
			result.setStatus(DataStatus.ERROR);
			result .setMessage("没有相应的借阅记录");
			return result;
		} 
		
		//借阅记录
		CoreCirculationLog cr = new CoreCirculationLog(); 
		cr.setId(UUIDUtils.random());
		cr.setBookId(book.getId());  
		cr.setReaderId(user.getReader().getId());
		cr.setTerminalId(terminal.getId());
		cr.setTerminalType(terminal.getType());
		cr.setRecordDate(new Date());
		cr.setRecordType(RecordType.REVEW); 
		cr.setRemark(terminal.getRemark() == null ? "" :terminal.getRemark().toString());  
		//当前记录  
		crecord.setBorrowType(BorrowType.REVEW); 
		crecord.setIsRenewed(true);
		crecord.setNeedReturnDate(null);
		crecord.setReaderId(user.getReader().getId());
		crecord.setRecordId(cr.getId());
		crecord.setRemark(terminal.getRemark() == null ? "" :terminal.getRemark().toString()); 
		crecord.setTerminalId(terminal.getId());
		crecord.setTerminalType(terminal.getType()); 
		crecord.setNeedReturnDate(book.getNeedReturnDate() == null ? new Date() : book.getNeedReturnDate());
		crecord.setBorrowDate(book.getOccurDate() == null ? new Date() : book.getOccurDate());
		 
		
		try{ 
			//保存记录信息
			coreRecordDao.insert(cr); 
			//更新借阅当前信息  
			coreCurrentRecordDao.updateByPrimaryKeySelective(crecord); 
			//更新图书状态(后期将不再使用)以当前记录为标准
			sysBookinfoDao.updateStatusByRFID(book); 
			
			result.setStatus(DataStatus.OK);
			result.setMessage("借阅成功"+getCheckOutMsg(crecord.getBookName(),user.getReader().getDzmc(),
					DateFormat.dateToString(crecord.getBorrowDate(),DateFormat.FORMATDATE),
					DateFormat.dateToString(crecord.getNeedReturnDate(),DateFormat.FORMATDATE))); 
		}catch(Exception ex)
		{
			log.error("续借异常："+ex.getMessage()); 
			result.setStatus(DataStatus.ERROR);
			result.setMessage("续借异常："+ex.getMessage()); 
			throw new ServiceException(ex); 
		} */
		return result;
	}

	@Override
	public SysBook getBookInfo(SysBook entity) {  
		return sysBookinfoDao.selectOne(entity);   
	}
	
	@Override
	public DataResult doQuery(String openId) { 
		SysReaderWechat srw = null;//readerWechatDao.selectByAppid(openId); 
		LoginUser user = new LoginUser();
		user.setReader(srw.getReader());
		return doQuery(getTerminal("微信查询"),user);
	} 

	@Override
	public DataResult doQuery(Terminal terminal, LoginUser user) {
		//返回信息
		DataResult result = new DataResult();  
		/*//借阅记录
		CoreCirculationLog cr = new CoreCirculationLog();  
		cr.setBookId("");  
		cr.setReaderId(user.getReader().getId());
		cr.setTerminalId(terminal.getId());
		cr.setTerminalType(terminal.getType());
		cr.setRecordDate(new Date());
		cr.setRecordType(RecordType.QUERY); 
		cr.setRemark(terminal.getRemark() == null ? "" :terminal.getRemark().toString()); 
		
		CoreCurrentrecord crecord = new CoreCurrentrecord();
		crecord.setReaderId(user.getReader().getId());
		try{ 
			//保存记录信息
			coreRecordDao.insert(cr);  
			//查询借阅当前信息  
			List<CoreCurrentrecord> list = coreCurrentRecordDao.select(crecord); 
			result.setStatus(DataStatus.OK);
			result.setData(list); 
		}catch(Exception ex)
		{
			log.error("执行查询异常："+ex.getMessage()); 
			result.setStatus(DataStatus.ERROR);
			result.setMessage("执行查询异常："+ex.getMessage()); 
			throw new ServiceException(ex); 
		} */
		return result;
	}
	
	/***
	 * 获取请求信息
	 * @param uid 用户cardid
	 * @param pwd 密码
	 * @param bookid barcode或bookid
	 * @return
	 * @date 2016-8-18 下午2:23:35
	 */
	private LibraryRequest getLibraryRequest(String uid,String pwd,String bookid)
	{
		LibraryRequest req = new LibraryRequest();
		req.setSzUserId(uid);
		req.setSzUserPWD(pwd);
		req.setInstitutionId("");
		//req.setBookid(bookid);
		//req.setScLocation("wechat"); 
		//req.setSysConfig(getSysConfig());
		return req;
	}
	
	/***
	 * 查询系统配置信息
	 * @return
	 * @date 2016-8-18 下午2:22:47
	 */
	private SysConfig getSysConfig()
	{
		SysConfig sysConfig = null;
		try{
			//sysConfig = sysConfigDao.selectByPrimaryKey(Const.SysId); 
			System.out.println("系统配置："+sysConfig);
		}catch(Exception ex)
		{
			log.error("查询系统配置信息异常:"+ex.getMessage());
			sysConfig = null;
		}
		return sysConfig;
	}

	@Override
	public DataResult doCheckOut(SysReader reader, String bookid) { 
		SysBookVo book = new SysBookVo();
		book.setBarcode(bookid);
		//查询图书信息
		book = sysBookinfoDao.selectOne(book); 
		if(book == null) 
			return new DataResult(DataStatus.ERROR,"不存在图书信息"); 
		//为了兼容图书管理系统，需要对其进行借还
		LibraryRequest request = getLibraryRequest(reader.getRfidCardNum(),reader.getPassword(),bookid);
		CheckOutResponse response = null;//libraryService.borrowBook(request);
		if(null == response) 
			response = new CheckOutResponse();
		//日志记录进行借阅图书管理系统提交失败
		if(response.getStatus() != 1) 
			log.info(String.format("提交图书管理系统借阅失败bookid: %s ,reader: %s ",bookid,reader.getReaderName())); 
		//进行金至借阅
		LoginUser user = new LoginUser();
		user.setReader(reader); 
		//设置图书管理软件返回信息
		book.setOccurDate(DateFormat.stringToDate(response.getOccurDate()));
		book.setNeedReturnDate(DateFormat.stringToDate(response.getNeedReturnDate()));
		return doBorrowBook(book, getTerminal("微信借阅"), user);  
	}
	
	/***
	 * 获取终端信息
	 * @param remark
	 * @return
	 * @date 2016-8-18 上午10:34:24
	 */
	public Terminal getTerminal(String remark)
	{
		Terminal terminal = new Terminal();
		terminal.setId(UUIDUtils.create());
		terminal.setTerminalType(TerminalType.WECHAT); 
		//terminal.setRemark(remark);
		return terminal;
	}

	@Override
	public DataResult doRenew(SysReader reader, String bookid) {
		SysBookVo book = new SysBookVo();
		book.setBarcode(bookid);
		//查询图书信息 不存在就不进行业务
		book = sysBookinfoDao.selectOne(book); 
		if(book == null) 
			return new DataResult(DataStatus.ERROR,"不存在图书信息"); 
		//为了兼容图书管理系统，需要对其进行借还
		LibraryRequest request = getLibraryRequest(reader.getRfidCardNum(),reader.getPassword(),bookid);
		CheckOutResponse response = null;//libraryService.reNewBook(request);
		if(null == response) 
			response = new CheckOutResponse();
		//日志记录进行借阅图书管理系统提交失败
		if(response.getStatus() != 1) 
			log.info(String.format("提交图书管理系统续借失败bookid: %s ,reader: %s",bookid,reader.getReaderName())); 
		//进行金至借阅
		LoginUser user = new LoginUser();
		user.setReader(reader);  
		//设置图书管理软件返回信息
		book.setOccurDate(DateFormat.stringToDate(response.getOccurDate()));
		book.setNeedReturnDate(DateFormat.stringToDate(response.getNeedReturnDate()));
		return doRenewBook(book, getTerminal("微信续借"), user);
	}

	@Override
	public DataResult addWechatUser(SysReader reader,String openId) {
		SysReaderWechat srw = null;//readerWechatDao.selectByAppid(openId);
		if(srw != null) 
			return new DataResult(DataStatus.ERROR,"您已经注册"); 
		
		SysReaderWechat rw = new SysReaderWechat();
		rw.setAppid(openId);
		rw.setConfigid(getSysConfig().getId());
		rw.setId(UUIDUtils.random());
		rw.setReader(reader); 
		rw.setRemark("微信注册用户"); 
		//更新原有用户信息
		SysReader rr = new SysReader();
		rr.setCampusCardNum(reader.getCampusCardNum());  
		rr = sysReaderService.queryOne(rr);
		if(rr == null)
			return new DataResult(DataStatus.ERROR,"注册用户失败,借阅证号不正确");
		//rr.setCellphone(reader.getCellphone()); 
		
		System.out.println(" get reader rr "+ rr);
		sysReaderService.updateByIdSelective(rr);
		
		rw.setReaderid(rr.getId());
		int b = 0;//readerWechatDao.insert(rw);
		//返回信息  
		if(b > 0)
			return new DataResult(DataStatus.OK,"注册用户成功");
		return new DataResult(DataStatus.ERROR,"注册用户失败");
	}

	@Override
	public DataResult doCheckIn(SysReader reader, String bookid) { 
		throw new NotImplementedException("");
	}

	/* (non-Javadoc)
	 * @see com.smforj.ssm.modules.wc.service.AppletService#getFollower(java.lang.String)
	 */
	@Override
	public DataResult<SysReader> getFollower(String appid) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.smforj.ssm.modules.wc.service.AppletService#getLibBook(java.lang.String)
	 */
	@Override
	public LibBookVo getLibBook(String code) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.smforj.ssm.modules.wc.service.AppletService#doCheckOut(java.lang.String, java.lang.String)
	 */
	@Override
	public DataResult<Integer> doCheckOut(String reader, String bookid) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.smforj.ssm.modules.wc.service.AppletService#doCheckIn(java.lang.String)
	 */
	@Override
	public DataResult<Integer> doCheckIn(String bookid) {
		// TODO Auto-generated method stub
		return null;
	} 

}
